package com.example.updatedemo;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.sample.download.DownloadInfo;
import com.lidroid.xutils.sample.download.DownloadManager;
import com.lidroid.xutils.sample.download.DownloadService;
import com.lidroid.xutils.util.LogUtils;


import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnLongClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class UpdateActivity extends Activity {

	private Button btn_quick_update;
	private TextView tv_update_count;
	private ListView lv_update, lv_update2;
	private MainApplication app;
	private UpdateQuickAdapter1 update_adapter1;
	private UpdateQuickAdapter2 update_adapter2;
	public static String btn_state = "display";
	private Context context;
	private String webService_ip, upgradeIp;
	private DownloadManager downloadManager;

	public ArrayList<T_Version> tempUpdateVersions = new ArrayList<T_Version>();
	private PackageReceiver packageReceiver;
	private ImageView update_imageview;
	private FrameLayout layout;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_update);
		context = this.getApplicationContext();
		app = (MainApplication) context;
		downloadManager = DownloadService.getDownloadManager(context);

		registerReciver();

		update_imageview = (ImageView)findViewById(R.id.update_imageview);
		btn_quick_update = (Button) findViewById(R.id.update_btn);
		lv_update = (ListView) findViewById(R.id.update_listview);
		// lv_update2 = (ListView)findViewById(R.id.update_listview2);
		tv_update_count = (TextView) findViewById(R.id.update_count);
		layout = (FrameLayout) findViewById(R.id.door_root_content_fl);
		
		lv_update.setVisibility(View.GONE);
		tv_update_count.setVisibility(View.GONE);
		btn_quick_update.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (btn_state.equals("display")) {
					FrameLayout.LayoutParams linearParams =  (FrameLayout.LayoutParams)layout.getLayoutParams();
				    linearParams.height = 450;
				    linearParams.width = 480;
				    layout.setLayoutParams(linearParams);
					update_imageview.setVisibility(View.GONE);
//					btn_quick_update.setText("开始升级");
					btn_quick_update.setBackgroundResource(R.drawable.btn_start_update);
					
					tv_update_count.setVisibility(View.VISIBLE);
					tv_update_count.setText("有" + app.updateVersions.size()
							+ "个模块需要升级");
					lv_update.setVisibility(View.VISIBLE);

					update_adapter1 = new UpdateQuickAdapter1(
							UpdateActivity.this, app.updateVersions,
							btn_quick_update);
					lv_update.setAdapter(update_adapter1);
					btn_state = "download";
				} else if (btn_state.equals("download")) {
//					btn_quick_update.setText("正在下载");
					btn_quick_update.setBackgroundResource(R.drawable.download_1);
					// tempUpdateVersions.clear();
					// update_adapter1.notifyDataSetChanged();
					// tv_update_count.setVisibility(View.VISIBLE);
					// tv_update_count.setText("有"+app.updateVersions.size()+"个模块需要升级");
					// lv_update.setVisibility(View.VISIBLE);
					// lv_update.setVisibility(View.GONE);
					// lv_update2.setVisibility(View.VISIBLE);
					deleteApk();
					download();
					update_adapter2 = new UpdateQuickAdapter2(
							UpdateActivity.this, downloadManager,
							app.updateVersions, btn_quick_update);

					lv_update.setAdapter(update_adapter2);
					lv_update
							.setSelection(lv_update.getAdapter().getCount() - 1);
					// btn_state = "install";
				} else if (btn_state.equals("install")) {
//					btn_quick_update.setText("正在安装");
					btn_quick_update.setBackgroundResource(R.drawable.install_1);
					update_adapter1 = new UpdateQuickAdapter1(
							UpdateActivity.this, app.updateVersions,
							btn_quick_update);
					lv_update.setAdapter(update_adapter1);
//					lv_update.setSelection(0);
//					lv_update
//							.setSelection(lv_update.getAdapter().getCount() - 1);

//					List<DownloadInfo> downloadInfoList = downloadManager
//							.getDownloadInfoList();
//					for (int i = 0; i < downloadInfoList.size(); i++) {
//						DownloadInfo info =  downloadInfoList.get(i);
//
//						String str = UpGradeUtil.installAPK(UpdateActivity.this,info.getFileSavePath());
//						app.updateVersions.get(i).setSavepath(str);
//						info.setFileSavePath(str);
//					}

						for (int i = 0; i < app.updateVersions.size(); i++) {
							T_Version version = app.updateVersions.get(i);
							String str_path = version.getSavepath();
							String str = null;
							if(str_path!=null)
							{
								if(new File(str_path).exists())
								{
									str = Utils.installAPK(UpdateActivity.this,str_path);
								}
							}
							
						}
					
					
					

				} else if (btn_state.equals("install_ok")) {
					UpdateActivity.this.finish();
				}

			}

		});

	}

	private void registerReciver() {
		IntentFilter filter = new IntentFilter();
		filter.addAction(Action.PACKAGE_ADDED_ACTION);
		filter.addAction(Action.PACKAGE_REMOVED_ACTION);
		filter.addDataScheme("package");
		packageReceiver = new PackageReceiver();
		this.registerReceiver(packageReceiver, filter);
	}
	@Override
	protected void onDestroy() {
	
		unregisterReceiver(packageReceiver);
		super.onDestroy();
	}

	/**
	 * @ClassName: PackageReceiver
	 * @Description: TODO监听安装和卸载应用广播
	 * @author Panyy
	 * @date 2013 2013-7-6 上午11:50:41
	 *
	 */
	public class PackageReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(Action.PACKAGE_ADDED_ACTION)) {
				String packageName = intent.getDataString();
				
					for (int i = 0; i < app.updateVersions.size(); i++) {
						T_Version version = app.updateVersions.get(i);
						String pack = version.getProduct();
						if(packageName.contains(pack))
						{
							version.setState("success");//保存安装完成的状态
							String str = version.getSavepath();
							if(str!=null)
							{
								Utils.deleteFile(new File(str));//删除安装完成的apk
							}
							
						}
					}
					if (update_adapter1 != null) {
						update_adapter1.notifyDataSetChanged();
					}
				}
				
			

			if (intent.getAction().equals(Action.PACKAGE_REMOVED_ACTION)) {
				if (update_adapter1 != null) {
					update_adapter1.notifyDataSetChanged();
				}
			}
		}
	}

	// 删除之前的apk文件
	private void deleteApk() {
		String str = Environment.getExternalStorageDirectory()
				.getAbsolutePath() + "/apkDownload/";
		File file = new File(str);
		if (!file.exists()) {
			file.mkdirs();
		}
		Utils.deleteFile(file);
	}

	public void download() {
		for (int i = 0; i < app.updateVersions.size(); i++) {

			T_Version version = app.updateVersions.get(i);
			String str = Environment.getExternalStorageDirectory()
					.getAbsolutePath() + "/apkDownload/";
			File file = new File(str);
			if (!file.exists()) {
				file.mkdirs();
			}
			String apkDownloadPath = version.getServerpath();
			final String apkSavePath = str
					+ version.getFilename()+".apk";
			
			version.setSavepath(apkSavePath);

			try {
				downloadManager.addNewDownload(apkDownloadPath,
						version.getFilename(), apkSavePath, true, // 如果目标文件存在，接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。
						false, // 如果从请求返回信息中获取到文件名，下载完成后自动重命名。
						null);
			} catch (DbException e) {
				LogUtils.e(e.getMessage(), e);
			}

		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) { // 监控/拦截/屏蔽返回键

			return false;
		} else if (keyCode == KeyEvent.KEYCODE_MENU) {
			
			
			return false;
		} else if (keyCode == KeyEvent.KEYCODE_HOME) {
			// 由于Home键为系统键，此处不能捕获，需要重写onAttachedToWindow()
			
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}

//	// 拦截/屏蔽系统Home键
//	public void onAttachedToWindow() {
//		this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
//		super.onAttachedToWindow();
//	}

}
